package MediaOnline.Adapter;


import MediaOnline.Data.userData;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {
	

	private SQLiteDatabase mDB;
	private Context mContext;
	private DBHelper mDBHelper;
	
	//Khai bao cac bien
	private final String DBName = "dbInfor";
	private final String tblInfor= "tblUserInfor";
	private final String clmUname = "Username";
	private final String clmPass = "Password";
	
	public static Cursor mCursor;
	
	public DBAdapter(Context c){
    	mContext=c;
    }
	
	private class DBHelper extends SQLiteOpenHelper{

		public DBHelper(Context context, String name, CursorFactory factory,
				int version) {
			super(context, name, factory, version);
			// TODO Auto-generated constructor stub
		}
		
		
		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL("Create table "+tblInfor+ "("+clmUname+" text primary key, "+clmPass+" text)");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL("Crop table if exist "+tblInfor);
			onCreate(db);	
		}	
	}
	
	//Insert tat ca du lieu lay ve tu webservice
	public void InsertData (){
		String Uname;
		String Pass;
		Log.d("InsertDATA arrUname size ::: ", ""+userData.arrUname.size());
		for (int i=0;i<userData.arrUname.size();i++){
			Uname = userData.arrUname.get(i).toString();
			Pass = userData.arrPass.get(i).toString();
			ContentValues cv = new ContentValues();
			cv.put(clmUname, Uname);
			cv.put(clmPass, Pass);
			mDB.insert(tblInfor, null, cv);
			Log.d("Note::::::", "Insert du lieu, dong " + i);
		}
	}
	
	//Dong db
	public void closeDB() {
		// TODO Auto-generated method stub
		mDBHelper.close();
	}
	
	//Mo db
	public void openDB()
	{
		mDBHelper = new DBHelper(mContext, DBName, null, 1);
		mDB = mDBHelper.getWritableDatabase();
	}
	
	//Lay du lieu
	public void getUser()
    {
        mCursor= mDB.query(tblInfor, new String[]{clmUname, clmPass}, null, null, null, null, null);
    }
	
	//Xoa du lieu hien tai
	public void ClearDB(){
		mDB = mDBHelper.getWritableDatabase();
		mDB.delete(tblInfor, null, null);
	}
	
}
